from itertools import count
import math
from logging import exception
import bleach
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q, Count, Value, F
from django.db.models.functions import Substr, Concat
from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_http_methods
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.urls import  reverse_lazy
from django.views import View

from Blog_Item import settings
from .forms import *
from blog.models import BlogCategory
from django.contrib.auth import get_user_model

User = get_user_model()
# Create your views here.
@require_http_methods(["GET"])
def search(request):
    key = request.GET.get('key')
    page = int(request.GET.get('page', 1))
    query = Blog.objects.order_by('-id').annotate(
            sub_content=Substr('content', 1, 1000),
            icon_url = Concat(Value(settings.MEDIA_URL),F("author__profile__icon"),output_field=models.CharField())
        )
    if key:
        query = query.filter(Q(title__icontains=key) | Q(content__icontains=key))
    paginator = Paginator(query,6)
    pages = paginator.count
    pages = pages if pages > 0 else 1
    current_page = paginator.get_page(page)
    blogs = current_page.object_list.values(
            'id', 'author__id', 'title', 'sub_content', 'pub_time', 'author__username','icon_url'
        )
    content={
        'no':False,
        'key':key,
        'blogs':blogs,
        'pages':pages,
        'page':page,
    }
    return render(request,'search.html',content)

def index(request):
    """
    纯纯二流子,写的什么鸡巴优化
    select blog_table.blog_id,blog_table.title,blog_table.pub_time,blog_table.content,blog_table.author_id,
    author_table.auth_username from

    (select blog_blog.id as blog_id,blog_blog.title as title ,blog_blog.pub_time as pub_time,
    blog_blog.content as content , blog_blog.author_id as author_id from blog_blog order by id desc limit 6)
    as blog_table

    inner join

    (select auth_user.id as auth_id,auth_user.username as auth_username from auth_user where id in(
        select author_id from blog_blog order by id desc limit 6
     )) as author_table

    on

    blog_table.author_id = author_table.auth_id;
    """
    blogs = Blog.objects.annotate(
        sub_content=Substr('content', 1, 1000),
        icon_url=Concat(Value(settings.MEDIA_URL),F("author__profile__icon"),output_field=models.CharField()),
    ).order_by('-id')[:6].values(
        'id', 'author__id', 'title', 'sub_content', 'pub_time', 'author__username',"icon_url"
    )
    for blog in blogs:
        blog['sub_content'] = bleach.clean(blog['sub_content'], tags=[], strip=True)
    context = {
        'blogs': blogs,
    }
    return render(request,'index.html',context)
def blog_detail(request, blog_id):
    blog = Blog.objects.get(id=blog_id)
    author = blog.author
    comment_num = blog.blogcomment_set.count()
    context = {
        'author': {
            'id': author.id,
            'username': author.username,
            'icon': author.profile.icon.url,
        },
        'blog': {
            'id': blog.id,
            'time': blog.pub_time,
            'title': blog.title,
            'content': blog.content,
            'category': blog.category.name,
        },
        'comment_num': comment_num,
    }
    return render(request,'blog_detail.html',context=context)
@login_required(login_url=reverse_lazy('userAuth:login'))
def pub_blog(request):
    categories = BlogCategory.objects.all()
    return render(request,'pub_blog.html',{'categories':categories})

class PubBlogAPI(View):
    def post(self,request):
        form = BlogForm(request.POST)
        if form.is_valid():
            category = BlogCategory.objects.get(id=form.cleaned_data['category'])
            blog = Blog(
                title=form.cleaned_data['title'],
                content=form.cleaned_data['content'],
                category=category,
                author=request.user
            )
            try:
                blog.save()
                return JsonResponse({'code': 200, 'blog_id': blog.id, 'msg': 'success'})
            except exception as e:
                pass
        return JsonResponse({'code':400,'msg':'<UNK>'})

class CommentBlogAPI(View):
    def post(self,request):
        if not request.user.is_authenticated:
            return JsonResponse({'code':302,'msg':'请登录'})
        form = BlogCommentForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['content']
            author = request.user
            blog = Blog.objects.get(id=form.cleaned_data['blog_id'])
            BlogComment.objects.create(content=comment,author=author,blog=blog)
            return JsonResponse({'code': 200, 'msg': 'success'})
        return JsonResponse({'code':400,'msg':form.errors})
class CommentMoreAPI(View):
    def get(self,request):
        blog = Blog.objects.get(id=request.GET.get('blog_id'))
        page = request.GET.get('page')
        query = blog.blogcomment_set.order_by('-id').annotate(
            icon_url=Concat(
                Value(settings.MEDIA_URL),
                F('author__profile__icon'),
                output_field=models.CharField()
            )
        )
        paginator = Paginator(query,10)
        try:
            page_content = paginator.page(page)
        except EmptyPage as e:
            return JsonResponse({'code':400,'msg':'你他妈是不是有病.改这个干嘛'})
        has_more = page_content.has_next()
        more_comments = list(page_content.object_list.values(
            'content',
            'pub_time',
            'author__username',
            'author__id',
            'icon_url'
        ))
        return JsonResponse({'code':200,"more_comments":more_comments,"has_more":has_more,})
